import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute} from "@angular/router";
import {BarnDocumentService} from "../service/barn-document.service";
import {BarnDocument} from "../entity/barn-document";
import * as DecoupledEditor from "../../../../../../assets/ckeditor5-build-decoupled-document/ckeditor";
import {tap} from "rxjs/operators";
import {fromPromise} from "rxjs/internal/observable/innerFrom";
import {forkJoin} from "rxjs";
import {BarnProject} from "../../project/entity/barn-project";

@Component({
  selector: 'app-document-preview',
  templateUrl: './document-preview.component.html',
  styleUrls: ['./document-preview.component.less']
})
export class DocumentPreviewComponent implements OnInit {

  loading = false

  document: BarnDocument = new BarnDocument();

  editor;
  @ViewChild("editor", {static: true})
  editorHolder;

  projects:BarnProject[] = []

  constructor(private routeInfo: ActivatedRoute, private documentService: BarnDocumentService) {
  }

  ngOnInit(): void {
    const pid = this.routeInfo.snapshot.queryParams["pid"];
    let getById$ = null
    if (pid) {
      this.loading = true
      getById$ = this.documentService.getById(pid)
        .pipe(tap(value => {
          this.loading = false
          this.document = value
        }))
    }
    const editorPromise = this.initEditor();
    if (pid) {
      const editor$ = fromPromise(editorPromise);
      forkJoin<any[]>([editor$, getById$]).subscribe(value => {
        const data = value[1]
        this.editor.setData(data['documentText'])
      });
    }
  }

  initEditor() {

    return DecoupledEditor
      .create(this.editorHolder.nativeElement, {})
      .then(editor => {
        this.editor = editor;
        this.editor.isReadOnly = true
      })
      .catch(err => {
        console.error(err);
      })
  }

}
